package com.springcloud.security;

import com.springcloud.service.ISysResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @program: springcloud
 * @description: 自定义的Metadata，通过当前请求地址，获取该地址所需要的角色
 * @author: paddy
 * @create: 2019-04-15 12:56
 **/
@Service
public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {

    @Autowired
    ISysResourceService resourceService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {

        //object 中包含用户请求的request 信息
        HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
        String uri = request.getRequestURI();
        List<String> roleNameList = resourceService.selectRoleNamesByURI(uri); // 查出资源所需要的角色
        if(roleNameList!=null){
            List<ConfigAttribute> attributes = new ArrayList();
            for(String roleName:roleNameList){
                attributes.add(new SecurityConfig(roleName));
            }
            return attributes;
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
